#include <winsock2.h>
#include <stdio.h>


#pragma comment(lib, "ws2_32.lib")
#define DEFAULT_BUFFER      100

void main()
{
	WORD		wVersionRequested;
	WSADATA		wsaData;
	int		err;

	wVersionRequested = MAKEWORD(1, 1);

	err = WSAStartup(wVersionRequested, &wsaData);
	if (err != 0)
	{
		return ;
	}

	if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
	{
		WSACleanup();
		return ;
	}

	SOCKET	sockclient = socket(AF_INET, SOCK_DGRAM, 0);

	SOCKADDR_IN	addrsrv;
	addrsrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	addrsrv.sin_family = AF_INET;
	addrsrv.sin_port   = htons(6000);

	bind (sockclient, (SOCKADDR*)&addrsrv, sizeof(SOCKADDR));

	char	recvbuf[DEFAULT_BUFFER],
		sendbuf[DEFAULT_BUFFER],
		tempbuf[DEFAULT_BUFFER];

	int len = sizeof(SOCKADDR);

	while(1)
	{
		printf("Please input data: \n");
		gets(sendbuf);
		sendto(sockclient, sendbuf, strlen(sendbuf)+1, 0, (SOCKADDR*)&addrsrv, len);

		recvfrom(sockclient, recvbuf, DEFAULT_BUFFER, 0, (SOCKADDR*)&addrsrv, &len);

		if (recvbuf[0] = 'q')
		{
			sendto(sockclient, "q", strlen("q")+1, 0, (SOCKADDR*)&addrsrv, len);
			printf("chat end ! \n");
			break;
		}

		sprintf(tempbuf, " %s say : %s", inet_ntoa(addrsrv.sin_addr), recvbuf);
		printf("%s\n", tempbuf);
	}

	closesocket(sockclient);

	WSACleanup();
}